<template>
  <a-space>
    <a-radio-group type="button" v-model="searchValue.isSearchTermProduct" @change="getTableList">
      <a-radio :value="false">投放产生关键词</a-radio>
      <a-radio :value="true">投放产生ASIN</a-radio>
    </a-radio-group>
    <a-select v-model="searchValue.matchType" :style="{ width: '160px' }" allow-clear placeholder="请选择">
      <a-option value="EXACT">精确</a-option>
      <a-option value="PHRASE">词组</a-option>
    </a-select>
    <filterKeywordByType ref="FilterKeywordByType" :currentItem="keyWordSearchType" @search="selectMulVal($event, keyWordSearchType, 'hasSearchType')" />
    <a-range-picker v-model="searchValue.time" :style="{ width: 300 + 'px' }" :allow-clear="false" shortcuts-position="left" :shortcuts="rangeShortcuts()" />
    <a-button class="gray-outline" @click="search">搜索</a-button>
  </a-space>

  <showStatics class="mt5" :list="list" />

  <a-space class="mt5">
    <!-- <a-button class="gray-outline">归档</a-button> -->
    <a-button type="primary" v-if="!searchValue.isSearchTermProduct" @click="openAddKeyword">添加至否定词</a-button>
    <!-- <a-button type="primary">添加否至定商品</a-button> -->
    <a-button type="primary" v-if="!searchValue.isSearchTermProduct" @click="batchAddNegativeKeyword">添加至关键词</a-button>
    <!-- <a-button type="primary">添加至投放商品</a-button> -->
  </a-space>

  <a-table class="mt5" row-key="id" :loading="tableLoading" size="mini" @sorter-change="sorterChange" :row-selection="{ type: 'checkbox', showCheckedAll: true, onlyCurrent: false }" v-model:selectedKeys="ids" :pagination="false" :data="tableDate" :scroll="{ y: '300px', x: '100%' }">
    <template #columns>
      <!-- 搜索词为ASIN -->
      <a-table-column v-if="searchValue.isSearchTermProduct" :width="60" title="图片" data-index="searchAsinImageUrl" key="searchAsinImageUrl" fixed="left">
        <template #cell="{ record }">
          <ImgPopover :src="record.searchAsinImageUrl || record.searchAsinSmallImageUrl" :isPre="true">
            <template #con>
              <a-image width="40" :preview="false" height="40" fit="contain" :src="record.searchAsinSmallImageUrl || record.searchAsinImageUrl" />
            </template>
          </ImgPopover>
        </template>
      </a-table-column>
      <a-table-column :width="200" title="买家搜索词" fixed="left">
        <template #title>
          <a-popover>
            <template #content>
              <p style="width: 400px">与广告组中关键词匹配的买家搜索词，搜索词是买家在亚马逊上搜索商品时输入的确切词语组合</p>
            </template>
            <p>
              <span>买家搜索词</span>
              <icon-question-circle />
            </p>
          </a-popover>
        </template>
        <template #cell="{ record }">
          <a-typography-paragraph v-if="record.isSearchTermProduct" copyable :copy-text="record.searchAsinUrl" style="margin-bottom: 0" :copy-tooltip-props="{ mini: true }">
            <p class="highlight searchTerm" :class="{ isAdd: record.targetMatchTypeCn }">{{ record.searchTerm }}</p>
          </a-typography-paragraph>
          <p v-else :class="{ isAdd: record.targetMatchTypeCn }" class="searchTerm">{{ record.searchTerm }}</p>
          <p v-if="record.targetMatchTypeCn">
            <span class="targetMatchTypeCn">{{ record.targetMatchTypeCn }}</span>
          </p>
        </template>
      </a-table-column>

      <a-table-column :width="160" title="投放目标" fixed="left">
        <template #cell="{ record }">
          <!-- 商品投放显示 -->
          <div class="flex-c" v-if="record.targetingObjType == 'PRODUCT'">
            <ImgPopover :src="record.asinImageUrl || record.asinSmallImageUrl" :isPre="true">
              <template #con>
                <a-image width="40" :preview="false" height="40" fit="contain" :src="record.asinSmallImageUrl || record.asinImageUrl" />
              </template>
            </ImgPopover>
            <div>
              <a-typography-paragraph copyable :copy-text="record.asinUrl" style="margin-bottom: 0" :copy-tooltip-props="{ mini: true }">
                <a-button style="line-height: 20px; height: 20px" type="text">{{ record.targeting }}</a-button>
              </a-typography-paragraph>
              <p style="color: #999">{{ SearchTermTargetingObjType[record.targetingObjType] || record.targetingObjType }}</p>
            </div>
          </div>
          <template v-else>
            <TextLimit :rows="1">{{ record.targeting || '--' }}</TextLimit>
            <p style="color: #999">{{ SearchTermTargetingObjType[record.targetingObjType] || record.targetingObjType }}</p>
          </template>
        </template>
      </a-table-column>
      <a-table-column :width="75" title="匹配类型">
        <template #cell="{ record }">
          <p v-if="KeywordMatchType[record.matchType]">{{ KeywordMatchType[record.matchType] }}匹配</p>
        </template>
      </a-table-column>
      <a-table-column data-index="adType" :width="80" title="活动类型">
        <template #cell="{ record }">
          <p>{{ AdTypes[record.adType] }} </p>
        </template>
      </a-table-column>
      <a-table-column :sortable="sortable" data-index="bid" align="right" :width="100" title="目标竞价">
        <template #title>
          <a-popover content="当此投放触发您的广告时您将为一次点击支付的最高金额">
            <p>
              <span>目标竞价</span>
              <icon-question-circle />
            </p>
          </a-popover>
        </template>
        <template #cell="{ record }">
          <p>
            <span>{{ getCurrencySymbol(record.marketplaceId) }}</span>
            <span>{{ record.bid }}</span>
          </p>
        </template>
      </a-table-column>
      <a-table-column :width="85" :sortable="sortable" align="right" title="曝光量" data-index="impressions">
        <template #cell="{ record }">
          <p v-if="record.impressions || record.impressions === 0">{{ record.impressions }}</p>
          <p v-else>--</p>
        </template>
      </a-table-column>
      <a-table-column :width="85" align="right" :sortable="sortable" title="点击量" data-index="clicks">
        <template #cell="{ record }">
          <p v-if="record.clicks || record.clicks === 0">{{ record.clicks }}</p>
          <p v-else>--</p>
        </template>
      </a-table-column>
      <a-table-column :width="80" title="CTR" align="right" :sortable="sortable" data-index="ctr">
        <template #cell="{ record }">
          <p v-if="record.ctr || record.ctr === 0">{{ Number(record.ctr).toFixed(2) }}%</p>
          <p v-else>--</p>
        </template>
      </a-table-column>
      <a-table-column :width="95" title="广告销量" align="right" :sortable="sortable" data-index="purchasesSale">
        <template #cell="{ record }">
          <p v-if="record.purchasesSale || record.purchasesSale === 0">{{ record.purchasesSale }}</p>
          <p v-else>--</p>
        </template>
      </a-table-column>
      <a-table-column :width="80" title="CVR" align="right" :sortable="sortable" data-index="cvr">
        <template #cell="{ record }">
          <p v-if="record.cvr || record.cvr === 0">{{ Number(record.cvr).toFixed(2) }}%</p>
          <p v-else>--</p>
        </template>
      </a-table-column>
      <a-table-column :width="85" title="花费" align="right" :sortable="sortable" data-index="cost">
        <template #cell="{ record }">
          <p v-if="record.cost || record.cost === 0">${{ Number(record.cost).toFixed(2) }}</p>
          <p v-else>--</p>
        </template>
      </a-table-column>
      <a-table-column :width="80" title="CPC" align="right" :sortable="sortable" data-index="cpc">
        <template #cell="{ record }">
          <p v-if="record.cpc || record.cpc === 0">${{ Number(record.cpc).toFixed(2) }}</p>
          <p v-else>--</p>
        </template>
      </a-table-column>
      <a-table-column :width="120" title="广告销售额" align="right" :sortable="sortable" data-index="saleAmount">
        <template #cell="{ record }">
          <p v-if="record.saleAmount || record.saleAmount === 0">${{ Number(record.saleAmount).toFixed(2) }}</p>
          <p v-else>--</p>
        </template>
      </a-table-column>
      <a-table-column :width="85" title="ACOS" align="right" :sortable="sortable" data-index="acos">
        <template #cell="{ record }">
          <p v-if="record.acos || record.acos === 0">{{ Number(record.acos).toFixed(2) }}%</p>
          <p v-else>--</p>
        </template>
      </a-table-column>
      <a-table-column :width="85" title="ROAS" align="right" :sortable="sortable" data-index="roas">
        <template #cell="{ record }">
          <p v-if="record.roas || record.roas === 0">{{ Number(record.roas).toFixed(2) }}</p>
          <p v-else>--</p>
        </template>
      </a-table-column>
    </template>
  </a-table>
  <div class="pagination-footer mt10">
    <a-pagination size="mini" :total="pagination.total" :default-page-size="pagination.pageSize" :current="pagination.pageNum" :page-size-options="[20, 50, 100, 200, 300]" show-total show-page-size @page-size-change="sizeChange" @change="changePage" />
  </div>

  <!-- 添加关键词 -->
  <AddKeywordBySearchVal v-if="showAddKeyword" :shopList="shopList" :list="selectRows" :isShow="showAddKeyword" @closed="showAddKeyword = false" @success="getTableList" />
  <!-- 添加否定关键词 -->
  <AddNegativeKeyword v-if="showAddNegativeKeyword" :level="props.info.currentLevel" type="add" :isShow="showAddNegativeKeyword" :shopList="shopList" :defaultVal="defaultVal" @closed="showAddNegativeKeyword = false" />
</template>

<script lang="ts" setup>
  import { reactive, ref, onMounted } from 'vue'
  import { rangeShortcuts, getStartAndEndTime } from '../../../common'
  import { KeywordMatchType, SearchTermTargetingObjType, AdTypes } from '../../../types'
  import { searchTermList, searchTermMetrics } from '@/api/advert'
  import { marketPlaceList, currencySymbol } from '@/utils/globalData'
  import { Message } from '@arco-design/web-vue'
  import showStatics from './showStatics.vue'
  import filterKeywordByType from '@/components/Form/filterKeywordByType.vue'
  import AddKeywordBySearchVal from '../addKeywordBySearchVal.vue'
  import AddNegativeKeyword from '../addNegativeKeyword.vue'
  import useBaseDataStore from '@/store/modules/base-data'
  import { uuid } from '@/utils'
  const props = defineProps(['info'])
  const FilterKeywordByType = ref()
  const useBaseData = useBaseDataStore()
  const sortable: any = reactive({
    sortDirections: ['descend', 'ascend'],
    sorter: true,
  })

  let searchValue: any = ref({
    matchType: '',
    isSearchTermProduct: false,
    time: getStartAndEndTime('last_30_days'),
    orderItems: null,
  })

  let pagination = ref({ total: 0, pageSize: 20, pageNum: 1 })

  let list = ref([
    { key: 'impressions', name: '曝光量', currency: '', num: '', isCount: true },
    { key: 'clicks', name: '点击量', currency: '', num: '', isCount: true },
    { key: 'ctr', name: '点击转化率CTR', currency: '', num: '', isCount: false, isPercentage: true },
    { key: 'purchasesSale', name: '广告销量', currency: '', num: '', isCount: true },
    { key: 'cvr', name: '销量转化率CVR', currency: '', num: '', isCount: false, isPercentage: true },
    { key: 'cost', name: '花费', currency: '$', num: '', isCount: true },
    { key: 'cpc', name: 'CPC', currency: '$', num: '', isCount: false },
    { key: 'saleAmount', name: '广告销售额', currency: '$', num: '', isCount: true, isPercentage: true },
    { key: 'acos', name: 'ACOS', currency: '', num: '', isCount: false },
    { key: 'roas', name: 'ROAS', currency: '', num: '', isCount: false },
  ])

  let keyWordSearchType = ref({
    type: 'input_keyword_type',
    key: 'searchTerm',
    keyItems: [{ label: '搜索词', value: 'searchTerm' }],
    keyWidth: '120',
    value: ref(),
    placeholder: '请输入',
    label: '',
    width: 160,
    isMultiple: false,
  })

  let tableLoading = ref(false)
  let showAddKeyword = ref(false)
  let showAddNegativeKeyword = ref(false)
  let ids = ref([])
  let selectRows = ref([])
  let tableDate = ref([])
  let defaultVal = ref('')
  let shopList = ref<Array<any>>([])

  const search = () => {
    let obj = FilterKeywordByType.value.selInfo
    searchValue.value.keywordText = obj.value
    searchValue.value.keywordIsTheSearchAccurate = obj.searchType == 'exact' ? true : false
    getTableList()
    getMetricsData()
  }

  const sizeChange = (val: number) => {
    pagination.value.pageNum = 1
    pagination.value.pageSize = val
    getTableList()
  }
  const changePage = (val: number) => {
    pagination.value.pageNum = val
    getTableList()
  }

  const selectMulVal = (searchVal: any, item: any, type?: string) => {
    if (type) {
      keyWordSearchType.value.value = searchVal.value
    } else {
      item.value = searchVal
    }

    search()
  }

  // 排序
  const sorterChange = (dataIndex: string, direction: string) => {
    if (!direction) {
      searchValue.value.orderItems = null
    } else {
      searchValue.value.orderItems = [
        {
          asc: direction == 'ascend' ? true : false,
          column: dataIndex,
        },
      ]
    }
    getTableList()
  }

  const getMetricsData = async () => {
    let params = {
      campaignIds: [props.info.campaignId],
      startDate: searchValue.value.time[0],
      endDate: searchValue.value.time[1],
      isSearchTermProduct: searchValue.value.isSearchTermProduct,
      keywordIsTheSearchAccurate: searchValue.value.keywordIsTheSearchAccurate,
      searchTerm: searchValue.value.keywordText,
      matchType: searchValue.value.matchType,
    }
    const res: any = await searchTermMetrics(params)
    list.value.forEach((e: any) => {
      e.num = res.data[e.key]
    })
  }

  const getTableList = async () => {
    let params = {
      ...searchValue.value,
      campaignIds: [props.info.campaignId],
      pageNum: pagination.value.pageNum,
      pageSize: pagination.value.pageSize,
      startDate: searchValue.value.time[0],
      endDate: searchValue.value.time[1],
      searchTerm: searchValue.value.keywordText,
      orderItems: searchValue.value.orderItems,
    }
    tableLoading.value = true
    const res: any = await searchTermList(params)
    tableLoading.value = false
    selectRows.value = []
    ids.value = []
    if (res) {
      pagination.value.total = res?.data?.total
      tableDate.value = res.data.data || []
      tableDate.value.forEach((el: any) => {
        el.id = el.id = uuid()
      })
    }
  }

  // 显示货币符号
  function getCurrencySymbol(marketplaceId: any) {
    let currency = marketPlaceList[marketplaceId]?.currency
    return currencySymbol[currency]
  }

  async function getShopList() {
    await useBaseData.getShopList()
    shopList.value = useBaseData.shopList
  }

  function openAddKeyword() {
    if (!ids.value.length) {
      return Message.error('请选择搜索词')
    }
    if (ids.value.length > 10) {
      return Message.error('一次最多只能添加10个，请分批操作')
    }
    ids.value.forEach((el: any) => {
      let item = tableDate.value.find((e: any) => e.id == el)
      if (item) selectRows.value.push(item)
    })
    showAddKeyword.value = true
  }

  // 添加到否定关键词投放
  function batchAddNegativeKeyword() {
    if (!ids.value.length) {
      return Message.error('请选择需要添加的搜索词')
    }
    ids.value.forEach((el: any) => {
      let item = tableDate.value.find((e: any) => e.id == el)
      if (item) selectRows.value.push(item)
    })
    let nameArr = selectRows.value.map((el: any) => el.searchTerm)
    defaultVal.value = nameArr.join('\n')
    showAddNegativeKeyword.value = true
  }

  onMounted(() => {
    getTableList()
    getMetricsData()
    getShopList()
  })
</script>

<style lang="less" scoped>
  :deep(.arco-radio-group-button) {
    padding: 0;
    // margin-bottom: 10px;
    margin-right: 10px;
    .arco-radio-button {
      margin: 0;
      background-color: #fff;
      line-height: 30px;
      border: 1px solid var(--color-border);
      &:first-child {
        border-radius: 5px 0 0 5px;
      }
      &:last-child {
        border-radius: 0 5px 5px 0;
      }
    }
    .arco-radio-checked {
      border-color: rgb(var(--primary-6));
    }
  }
</style>
